<template>
  <el-upload
    class="upload-demo"
    :action="uploadurl"
    ref="upload"
    :on-remove="handleRemove"
    :auto-upload="false"
    :multiple="config.multiple"
    :on-success="fileUploadResult"
    :on-error="fileUploadError"
    :before-upload="fileCheck"
    :on-preview="filePreview">
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
    <div slot="tip" class="el-upload__tip">{{tipmsg}}</div>
  </el-upload>
</template>
<script>
  /*
     组件说明：
     1.输入参数为config 包含
  */
  import { createUploadUrl } from '../../assets/js/post.js'

  export default {
    name: 'upload',
    props: ['config'],
    data () {
      return {
        uploadurl: '',
        imageMaxSize: 2097152,
        attchmentMaxSize: 10485760,
        tipmsg: '',
        attchmentAllowType: ['xls', 'xlsx', 'doc', 'docx', 'pdf', 'rar', 'zip'],
        imgAllowType: ['image/jpeg', 'image/png']
      }
    },
    created () {
      switch (this.config.type) {
        case 'IMAGE':
          this.tipmsg = '只能上传单张jpg/png文件，且不超过2M'
          break
        case 'ATTCHMENT':
          this.tipmsg = '只能上传单张jpg/png文件，且不超过10M'
        case 'HeadPortrait':
          this.tipmsg = ''
          break
      }
      this.uploadurl = createUploadUrl(this.config.type)
    },
    methods: {
      submitUpload () {
        this.$refs.upload.submit()
      },
      fileCheck (file) {
      },
      handleRemove (file, fileList) {
        // this.$emit("removefile",fileList);
      },
      fileUploadResult (response, file, fileList) {
        if (response.status == '0') {
          this.$emit('getuplodfile', response)
        }
        else {
          this.$message({
            type: 'error',
            message: '有上传文件存在格式错误,图片文件只能上传jpg/bmp/png文件,附件文件只能上传doc/docx/xls/xlsx/pdf/rar/zip'
          })
        }
      },
      fileUploadError (err, file, fileList) {
        // this.$emit("fileuploaderror",err);
      },
      filePreview (file) {
        window.location.href = file.url
      },
      isUploadAllow (type, filesuffix) {
        switch (type) {
          case 'HeadPortrait':
          case 'IMAGE':
            imgAllowType.forEach(function (val) {
              if (filesuffix == val) {
                return true
              }
              return false
            })

            break

          case 'ATTCHMENT':
            attchmentAllowType.forEach(function (val) {
              if (filesuffix == val) {
                return true
              }
              return false
            })

            break
        }
      }

    }
  }
</script>
